<template>
  <div>
    <a-card title="敏感词管理" style="width: 100%">
      <a-form-item label="净化网络，从我做起">
        <div>
          <template v-for="(tag, index) in sensitiveList || []">
            <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
              <a-tag :key="tag" color="#ff4d4f" class="cursor" :closable="true" @close="() => handleClose(tag)">
                {{ `${tag.slice(0, 20)}...` }}
              </a-tag>
            </a-tooltip>
            <a-tag v-else :key="tag" color="#ff4d4f" class="cursor" :closable="true" @close="() => handleClose(tag)">
              {{ tag }}
            </a-tag>
          </template>
          <a-input
              v-if="inputVisible"
              ref="input"
              type="text"
              size="small"
              :style="{ width: '78px' }"
              :value="inputValue"
              @change="handleInputChange"
              @keyup.enter="handleInputConfirm"
          />
          <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
            <a-icon type="plus" /> 添加
          </a-tag>
        </div>
      </a-form-item>
    </a-card>

    <a-card
        v-if="$store.state.user.loginUser.type === 1"
        title="头衔管理" style="width: 100%">
      <a slot="extra" href="javascript:void(0)" @click="showModal('insert',{})">添加</a>
      <a-table :columns="columns"
               :loading="isloading"
               :pagination="false"
               :data-source="rankPage.data"
               rowKey="id">
      <span slot="rankName" slot-scope="text, record">
        <a-tag class="cursor" :title="record.rankDesc" :color="record.rankColor">
          {{ record.rankName }}
        </a-tag>
      </span>
        <!--      操作-->
        <span slot="action" slot-scope="text, record">
      <a-space>
        <a-button type="primary"
                  :disabled="record.id === 1 && $store.state.user.loginUser.type !== 1" @click="clickHandler('edit',record)" size="small" icon="edit" title="编辑"></a-button>
        <a-button type="danger"
                  size="small"
                  icon="delete"
                  title="删除"
                  :disabled="record.id === 1 && $store.state.user.loginUser.type !== 1"
                  @click="clickHandler('remove',record)"></a-button>
      </a-space>
    </span>

        <template slot="footer">
          <a-pagination
              style="text-align: end"
              :page-size-options="['2', '4', '5']"
              :total="rankPage.total"
              show-size-changer
              :page-size="rankPage.pageSize"
              @showSizeChange="onPageSizeChangeHandler"
              @change="onPageChangeHandler"
          >
            <template slot="buildOptionText" slot-scope="props">
              <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
              <span v-if="props.value === '50'">全部</span>
            </template>
          </a-pagination>
        </template>
      </a-table>
      <!--    编辑模态框-->
      <a-modal
          :title="ModalText"
          :visible="visible"
          :confirm-loading="confirmLoading"
          okText="确认"
          okType="primary"
          cancelText="放弃"
          @ok="handleOk"
          @cancel="handleCancel"
      >
        <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
          <a-form-item label="头衔名称">
            <a-input
                v-decorator="['rankName', {
                initialValue: currentRank.rankName,
                rules: [{ required: true, message: '请输入头衔名称!' }] }]"
            />
          </a-form-item>

          <a-form-item label="头衔描述">
            <a-textarea placeholder="请输入头衔描述" :rows="4" v-decorator="['rankDesc', {
                initialValue: currentRank.rankDesc,
                rules: [{ required: true, message: '请输入头衔描述!' }] }]" />
          </a-form-item>

          <a-form-item label="头衔颜色">
            <a-input
                v-decorator="['rankColor', {
                initialValue: currentRank.rankColor,
                rules: [{ required: true, message: '请输入头衔颜色!' }] }]"
            />
          </a-form-item>

        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import {DEFAULT_PAGENUM, DEFAULT_PAGESIZE} from "@/constent";
import {getRankListPage, removeRank, updateRank} from "@/api/sys";
import {addSensitive, getSensitiveList, removeSensitive} from "../../api/sensitive";
const columns = [
  {
    title: '头衔编号',
    dataIndex: 'id',
    key: 'id',
    width:150,
    align:'center',
    scopedSlots: { customRender: 'id' },
  },
  {
    title: '头衔名',
    dataIndex: 'rankName',
    width:200,
    key: 'rankName',
    align:'center',
    scopedSlots: { customRender: 'rankName' },
  },
  {
    title: '头衔颜色',
    dataIndex: 'rankColor',
    width:150,
    key: 'rankColor',
    align:'center',
  },
  {
    title: '头衔描述',
    dataIndex: 'rankDesc',
    key: 'rankDesc',
    ellipsis: true,
    width:550,
    align:'center',
  },
  {
    title: '操作',
    key: 'action',
    align:'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
  },
];
export default {
name: "other",
  data(){
    return {
      // 敏感词管理
      inputVisible: false,
      inputValue: '',
      sensitiveList:[],
      // 头衔
      color1:'red',
      ModalText:'',
      isloading: false,
      rankPage:{
        total:20,
        pageNum:DEFAULT_PAGENUM,
        pageSize:DEFAULT_PAGESIZE,
      },
      columns,
      queryParam:{
        pageSize:DEFAULT_PAGESIZE,
        pageNum:DEFAULT_PAGENUM
      },
      // 编辑模态框是否显示
      visible: false,
      // 确认加载中
      confirmLoading: false,
      // 编辑菜单
      currentRank:{},
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
    }
  },
  watch:{
    // 监视参数变化
    queryParam:{
      immediate:true,
      deep:true,
      handler(){
        this.getRankList();
      }
    }
  },
  mounted() {
    this.initSensitiveList();
  },
  methods:{
    // 敏感词管理
    // 获取敏感词库
    async initSensitiveList() {
      const {code, data, msg} = await getSensitiveList();
      if (code === 200){
        this.sensitiveList = data;
      } else {
        this.$message.error(msg);
      }
    },
    // 移除标签
    async handleClose(removedTag) {
      const {code, msg} = await removeSensitive(removedTag);
      if (code === 200){
        const tags = this.sensitiveList.filter(tag => tag !== removedTag);
        this.sensitiveList = tags;
      } else {
        this.$message.error(msg);
      }
    },
    // 手动输入标签名改变事件
    handleInputChange(e) {
      this.inputValue = e.target.value;
    },

    // 回车或失去焦点添加标签
    async handleInputConfirm() {
      const inputValue = this.inputValue;
      const {code,data,msg} = await addSensitive(inputValue);
      if (code === 200){
        this.initSensitiveList();
        this.inputVisible = false;
        this.inputValue = '';
      } else {
        this.$message.error(msg);
      }
    },
    // 添加标签按钮是否显示
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function() {
        this.$refs.input.focus();
      });
    },
    // 头衔管理
    // 点击处理器
    clickHandler(opera,recode){
      if ('auth' === opera){
        this.showModal('auth',recode);
      } else if('edit' === opera){
        this.showModal('edit',recode);
      } else if('remove' === opera){
        this.remove(recode);
      }
    },
    // 获取头衔
    async getRankList(){
      this.isloading = true;
      const { pageNum,pageSize } = this.queryParam;
      const result = await getRankListPage(pageNum,pageSize);
      const { code,data,msg } = result;
      if (code === 200){
        this.isloading = false;
        this.rankPage = data;
      } else {
        this.$message.error(msg);
      }
    },
    // 删除头衔
    remove(record){
      const _this = this;
      this.$confirm({
        title: '删除头衔',
        content: '此操作将会删除该头衔,导致游湖头衔丢失,请谨慎操作?',
        okText: '确认',
        okType: 'danger',
        cancelText: '放弃',
        onOk() {
          removeRank(record.id).then(res => {
            const { code,msg } = res;
            if (code === 200){
              _this.$message.success(msg);
              _this.getRankList();
            } else {
              _this.$message.error(msg);
            }
          }).catch(error => {
            console.log(error);
            _this.$message.error("操作异常");
          })
        },
        onCancel() {
          console.log("取消了删除");
        },
      });
    },
    // 展示模态框
    async showModal(type,recode) {
      this.currentRank = recode;
      if ('edit' === type){
        this.ModalText = '编辑头衔';
        this.visible = true;
      } else if ('insert' === type){
        this.ModalText = '添加头衔';
        this.visible = true;
      }
    },
    // 点击了确定
    handleOk(e) {
      const _this = this;
      this.form.validateFields(async (err, values) => {
        if (!err) {
          _this.ModalText = '正在处理中...';
          _this.confirmLoading = true;
          let rank = {...values,id:_this.currentRank.id};
          const result = await updateRank(rank);
          const {code,msg} = result;
          if (code === 200){
            _this.$message.success(msg);
            _this.getRankList();
          } else {
            _this.$message.error(msg);
          }
          setTimeout(() => {
            _this.visible = false;
            _this.confirmLoading = false;
            _this.currentRank = {};
            _this.form.resetFields();
          }, 1000);
        }
      });
    },
    // 点击了取消
    handleCancel(e) {
      console.log('Clicked cancel button');
      this.visible = false;
    },
    /**
     * 每页显示条数改变回调
     * @param current
     * @param pageSize
     */
    onPageSizeChangeHandler(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.queryParam.pageNum = DEFAULT_PAGENUM;
    },

    /**
     * 当前页改变回调
     * @param current
     * @param pageSize
     */
    onPageChangeHandler(current){
      this.queryParam.pageNum = current;
    }
  }
}
</script>

<style scoped>

</style>
